<template>
  <div class="hot-ranking">
    <div class="ranking-container">
      <div class="section-header">
        <h2 class="section-title">热力排行</h2>
        <div class="section-tabs">
          <span class="tab" @click="newestRelease"  :class="{ active: activeTab === 'newest' }" >最热播放</span>
          <span class="tab" @click="hottestPlays" :class="{ active: activeTab === 'hottest' }">最新收藏</span>
        </div>
        <div class="section-actions">
          <span class="more-link" @click="goToMoreClick">更多 ></span>
        </div>
      </div>

      <div class="ranking-grid">
        <div 
          class="ranking-item" 
          v-for="(course, index) in videoDatas" 
          :key="index"
          @click="goToVideo(course)"
        >
          <div class="course-thumbnail" :ref="setThumbnailRef">
            <div class="course-image">
              <div class="rank-badge" :class="getRankClass(index)">
                {{ index + 1 }}
              </div>
               <div class="media-container">
                  <keep-alive>
                    <mini-video-player  v-if="hoverStates[index]"  :data="course" @timeupdateOther="onTimeUpdate" />
                    <template v-else>
                      <miku-image class="size-full" video :res-id="course.bannerId" draggable="false" />
                    </template>
                  </keep-alive>
               </div> 
            </div>
            <div class="course-duration">{{ displayDuration(course?.duration ?? 0*1000) }}</div>
          </div>
          <div class="course-info">
            <h3 class="course-title">{{ course.title }}</h3>
            <div class="course-meta">
              <span class="course-stats">{{ course.plays }} 次观看</span>
              <span class="course-date">{{ course.dynamic.publishTimeStr }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import videoApi from '@/apis/video';
import { displayDuration } from '@/utils/common';
// const pageSize = ref(20);
// const { state, execute, isLoading } = useAsyncState(()=>videoApi.getRecommend({ 
//   size: pageSize.value
// }), null, { 
//   resetOnExecute: false, 
// })
// console.log('video数据====',state)
const activeTab = ref<'newest' | 'hottest'>('newest') // 当前激活的选项卡
const videoDatas = ref<any[]>([]) // 展示的数据集

const thumbnailRefs = ref<HTMLElement[]>([])
const hoverStates = ref<boolean[]>([])

const params = ref({
  pageNum: 1,
  pageSize: 10,
  type: 'VIDEO',
  keyword: '',
  sort: 'STAR'
})
const setThumbnailRef = (el: HTMLElement | null) => {
  if (el) thumbnailRefs.value.push(el)
}

// 添加时间记录
const courseTimes = ref<Record<string, number>>({})
// 修改时间更新函数
const onTimeUpdate = (time: number, value: { sid: string }) => {
  courseTimes.value[value.sid] = time
}
// 生成视频链接
const generateVideoUrl = (course: object) => {
  let url = '/video/' + course.sid
  const currentTime = courseTimes.value[course.sid] || 0
  
  if (currentTime >= 3) {
    url += '#time' + currentTime
  }
  return url
}
onMounted(() => {
  
  hoverStates.value = new Array(thumbnailRefs.value.length).fill(false)
  
  thumbnailRefs.value.forEach((el, index) => {
    const isHovered = useElementHover(el, { 
      delayEnter: 200, 
      delayLeave: 200 
    })
    
    watch(isHovered, (value) => {
      hoverStates.value[index] = value
    })
  })
  newestRelease()
})

onBeforeUpdate(() => {
  thumbnailRefs.value = []
})

// 最新收藏
const  hottestPlays = async () => { 
  // if (!state.value) return
  activeTab.value = 'hottest'
  //   // 直接取前6条
  //   videoDatas.value = state.value.slice(0, 10)
  params.value.sort = 'STAR'
  const datas = await videoApi.search(params.value)
  if(datas){
    videoDatas.value = datas.records
  }
}
// 最热播放 
const newestRelease = async () => { 
  // if (!state.value) return
  activeTab.value = 'newest'
  // // 取最后6条（倒序排列）
  // videoDatas.value = [...state.value].reverse().slice(0, 10)
  params.value.sort = 'PLAY'
  const datas = await videoApi.search(params.value)
  if(datas){
    videoDatas.value = datas.records
  }
}

// 监听state变化初始化
// watch(() => state.value, (newVal) => {
//   if (newVal) {
//     // 默认显示最新发布
//     newestRelease()
//   }
// }, { immediate: true })
//点击视频
const  goToVideo = (value: Object) => {
  const url = generateVideoUrl(value)
  window.open(url, '_blank')
}

// 点击更多
const goToMoreClick = () => {
  const baseUrl = window.location.origin;
  const targetUrl = `${baseUrl}/search/video?kw=&sort=${params.value.sort}`;
  window.location.href = targetUrl;
}


interface HotCourse {
  title: string;
  duration: string;
  views: string;
  date: string;
}

const hotCourses = ref<HotCourse[]>([
  {
    title: '总第7课——西大数信教学学堂（复变函数）第1期——函数',
    duration: '05:28',
    views: '1.2万',
    date: '6-11'
  },
  {
    title: '总第7课——西大数信教学学堂（复变函数）第1期——函数',
    duration: '05:28',
    views: '1.2万',
    date: '6-11'
  },
  {
    title: '总第7课——西大数信教学学堂（复变函数）第1期——函数',
    duration: '05:28',
    views: '1.2万',
    date: '极6-11'
  },
  {
    title: '总第7课——西大数信教学学堂（复变函数）第1期——函数',
    duration: '05:28',
    views: '1.2万',
    date: '6-11'
  },
  {
    title: '总第7课——西大数信教学学堂（复变函数）第1期——函数',
    duration: '05:28',
    views: '1.2万',
    date: '6-11'
  },
  {
    title: '总第7课——西极数信教学学堂（复变函数）第1期——函数',
    duration: '05:28',
    views: '1.2万',
    date: '6-11'
  },
  {
    title: '总第7课——西大数信教学学堂（复变函数）第1期——函数',
    duration: '05:28',
    views: '1.2万',
    date: '6-11'
  },
  {
    title: '总第7课——西大数信教学学堂（复变函数）第1期——函数',
    duration: '05:28',
    views: '1.2万',
    date: '6-11'
  },
  {
    title: '总第7课——西大数信教学学堂（复变函数）第1期——函数',
    duration: '05:28',
    views: '1.2万',
    date: '6-11'
  },
  {
    title: '总第7课——西大数信教学学堂（复变函数）第1期——函数',
    duration: '05:28',
    views: '1.2万',
    date: '6-11'
  }
]);

function getRankClass(index: number): string {
  if (index === 0) return 'rank-gold';
  if (index === 1) return 'rank-silver';
  if (index === 2) return 'rank-bronze';
  return 'rank-normal';
}
</script>

<style scoped>
/* 保持原有样式不变 */
.hot-ranking {
  /* background: linear-gradient(135deg, #1a472a 0%, #2d5a4a 100%); */
  padding: 40px 0;
  position: relative;
  overflow: hidden;
  background-image: url('@/assets/images/hotBg.jpg');
  background-repeat: no-repeat;
  /* background-size: contain; */
  /* 添加背景色叠加来调整图片透明度 */
    background-color: rgba(0, 0, 0, 0.7); /* 70%不透明的黑色叠加 */
    background-blend-mode: overlay; /* 混合模式 */
    /* background-size: contain; */
}

.hot-ranking::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image: 
    radial-gradient(circle at 20% 80%, rgba(255, 255, 255, 0.1) 0%, transparent 50%),
    radial-gradient(circle at 80% 20%, rgba(255, 255, 255, 0.1) 0%, transparent 50%);
  pointer-events: none;
}

.ranking-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  position: relative;
  z-index: 1;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 30px;
}

.section-title {
  font-size: 24px;
  font-weight: bold;
  color: white;
  margin: 0;
}

.section-tabs {
  display: flex;
  gap: 20px;
  margin-left: 15px;
}

.tab {
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
  color: rgba(255, 255, 255, 0.7);
  border: 1极px solid rgba(255, 255, 255, 0.3);
}

.tab.active {
  background: rgba(255, 255, 255, 0.2);
  color: white;
  border-color: rgba(255, 255, 255, 0.5);
}

.tab:hover:not(.active) {
  background: rgba(255, 255, 255, 0.1);
}

.section-actions {
  margin-left: auto;
}

.more-link {
  color: white;
  font-size: 14px;
  cursor: pointer;
  text-decoration: none;
}

.more-link:hover {
  text-decoration: underline;
}

.ranking-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 20px;
}

.ranking-item {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  overflow: hidden;
  backdrop-filter: blur(10px);
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.ranking-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.3);
  border-color: rgba(255, 255, 255, 0.2);
}

.course-thumbnail {
  position: relative;
  height: 160px;
  background: rgba(0, 0, 0, 0.3);
}

.course-image {
  width: 100%;
  height: 100%;
  /* background: linear-gradient(135deg, rgba(255, 255, 255, 0.1) 0%, rgba(255, 255, 255, 0.05) 100%); */
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}
.media-container {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 1; /* 始终显示 */
  transition: all 0.3s ease;
  /* flex-shrink: 0;
  overflow: hidden; */
}
.size-full {
  width: 100%;
  height: 100%;
  object-fit: cover; /* 保持宽高比并填充容器 */
}

.rank-badge {
  position: absolute;
  top: 10px;
  left: 10px;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  font-weight: bold;
  color: white;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
  z-index: 3;
}

.rank-gold {
  /* background: linear-gradient(135deg, #ffd700 0%, #ffa500 100%); */
  background-color: #ef4455;
  box-shadow: 0 2px 8px rgba(255, 0, 0, 0.91);
}

.rank-silver {
  /* background: linear-gradient(135deg, #c0c0c0 0%, #a9a9a9 100%); */
  background-color: #b0622f;
  box-shadow: 0 2px 8px rgba(172, 109, 8, 0.808);
}

.rank-bronze {
  /* background: linear-gradient(135deg, #cd7f32 0%, #a0522d 100%); */
  background-color: #ffc54d;
  box-shadow: 0 2px 8px hsla(48, 98%, 48%, 0.904);
}

.rank-normal {
  /* background: rgba(255, 255, 255, 0.2); */
  background-color: #b1b1b1;
  box-shadow: 0 2px 8px #b1b1b1;
}

.course-duration {
  position: absolute;
  bottom: 10px;
  right: 10px;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.course-info {
  padding: 15px;
}

.course-title {
  font-size: 14px;
  color: white;
  margin: 0 0 10px 0;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.course-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: rgba(255, 255, 255, 0.7);
}

.course-stats {
  font-weight: 500;
}

.course-date {
  color: rgba(255, 255, 255, 0.6);
}

@media (max-width: 768px) {
  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .section-tabs {
    width: 100%;
    justify-content: space-between;
  }

  .section-actions {
    margin-left: 0;
    width: 100%;
    text-align: right;
  }

  .ranking-grid {
    grid-template-columns: 1fr;
  }
}
</style>